const path                        = require('path');
const pkg                         = require('../package.json');
const fs                          = require('fs')
const {uploadESApp} = require('../build/uploadESApp')
const readline = require('readline')
const { execSync,
} = require('child_process');
const {
  chdir,
  cwd,
  argv
} = require('process');
const { getFlavor } = require('./libs/flavorUtil');

console.log(`>>>>>>>buildFlavor argv:${argv}`)
let remark = ""
let uploadZip = false;
let flavors = []
let isProduction = false;
argv.forEach((val, index) => {
  if(index > 1){
    if(index === 2){
      uploadZip = (val === 'true')
    }else if(index === 3){
      isProduction = (val === 'true')
    }else{
      flavors.push(val)
    }
  }
});
const rl = readline.createInterface({
  input:process.stdin,
  output:process.stdout
})
if(isProduction){
  rl.question('确认发布到正式环境? y/n',(answer)=>{
    //console.info('answer:'+answer)
    if('y' === answer || 'Y' === answer){
      setNotes(rl)
      // process.exit(0)
    }else{
      process.exit(0)
    }
  })
}else{
  setNotes(rl)
  // process.exit(0)
}

function setNotes(rl){
  rl.question('请输入发布备注',(answer)=>{
    console.info('answer:'+answer)
    if('' !== answer){
      remark = answer
      startWork()
      process.exit(0)
    }else{
      process.exit(0)
    }
  })
}

function startWork(){
  console.log(`>>>>>>>buildFlavor flavor count:${flavors.length},array:${JSON.stringify(flavors)}`)

  let currentDir = path.resolve('./')
  let i = 0;
  try{
    fs.statSync('./dist/outputs')
    fs.rmSync('./dist/outputs',{recursive : true})
  }catch (e){}

  for(i = 0; i < flavors.length; i++){
    chdir(currentDir)
    let flavorName = flavors[i]
    try{
      fs.statSync('./dist/android')
      fs.rmSync('./dist/android',{recursive : true})
    }catch (e){}
    try{
      fs.statSync('./dist/android')
      fs.rmSync('./dist/android',{recursive : true})
    }catch (e){}

    process.env.flavor = flavors[i]
    // let flavorDir = path.resolve('./build/flavor',flavorName)
    // let flavorPath = path.resolve(flavorDir,'./config.json')
    console.log(`----------release build 第${i+1}个 flavor:${flavorName}----------`)
    console.log(`1 --> start build flavorName :${flavorName}`)
    // console.log(`release --> path:${flavorPath},flavorDir:${flavorDir}`)
    const flavor = getFlavor('./build/flavor',flavorName)

    //vendor
    execSync('webpack  --config ./scripts/hippy-webpack.android-vendor.js ')
    //buildFlavor
    execSync(`webpack --config ./build/buildFlavor.js`,{ stdio:'inherit' })
    uploadFlavor(flavor)
  }
}

function getGitCommit(){
  let cmd = 'git rev-list HEAD --count'

  let buffer = execSync(cmd)

  return parseInt(buffer.toString())
}

function uploadFlavor(flavor){
  // execSync('webpack --config build/buildFlavor.js ')
  console.log(`2 --> build done`)
  let buildDir = path.resolve(`./dist`)
  try{
    fs.mkdirSync(buildDir)
  }catch (e){}

  chdir(buildDir)
  let versionBase = pkg.version
  // let commitCount = getGitCommit()
  let commitCount = pkg.vercode
  if(commitCount < 0){
    console.log(`uploadFlavor fail access git commit error `)
    return
  }else{
    console.log(`uploadFlavor versionBase: `+versionBase+",commitCount :"+commitCount)
  }
  let pkgVersion = `${versionBase}.${commitCount}`
  console.log(`uploadFlavor finalVersion :${pkgVersion}`)
  //打包
  let outputName = `${flavor.packageName}-${pkgVersion}`
  execSync(`zip -q -r ${outputName}.zip ./android `)
  console.log(`3 --> zip done`)
  let outputsDir = path.resolve('./outputs')
  try{
    fs.mkdirSync(outputsDir)
  }catch (e){
  }
  fs.renameSync(`./${outputName}.zip`,path.resolve(outputsDir,`./${outputName}.zip`))
  chdir(outputsDir)
  //删除编译出来目录
  if(uploadZip){
    console.log(`4 --> start upload`)
    let filePath = path.resolve(`./${outputName}.zip`)
    uploadESApp(flavor.packageName,outputName,pkgVersion,filePath,isProduction,0,remark)
    console.log(`5 --> uploadDone`)
  }
}
